﻿using System;
using System.Text.RegularExpressions;

namespace SPContrib.Extensions
{
    /// <summary>
    /// Extensions for the String class
    /// </summary>
    public static class StringExtensions
    {
        /// <summary>
        /// Regular expression for a GUID
        /// </summary>
        private static Regex IsGuidRegex = new Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$", RegexOptions.Compiled);

        /// <summary>
        /// Returns the string as an exception
        /// </summary>
        /// <param name="args">optional args for string.format</param>
        public static Exception AsException(this string instance, params object[] args)
        {
            return new Exception(string.Format(instance, args));
        }

        /// <summary>
        /// Returns the string as an exception
        /// </summary>
        /// <param name="args">optional args for string.format</param>
        /// <param name="inner">an inner exception to append</param>
        public static Exception AsException(this string instance, Exception inner, params object[] args)
        {
            return new Exception(string.Format(instance, args), inner);
        }

        /// <summary>
        /// Converts the string to a Guid. If the string is not a valid GUID, Guid.Empty is returned
        /// </summary>
        public static Guid AsGuid(this string instance)
        {
            if (instance.IsGuid() == false)
            {
                return Guid.Empty;
            }

            return new Guid(instance);
        }

        /// <summary>
        /// Indicates if the string is a valid GUID (i.e. can be converted to a GUID)
        /// </summary>
        public static bool IsGuid(this string instance)
        {
            if (instance.IsNotNullOrEmpty())
            {
                return IsGuidRegex.Match(instance).Success;
            }

            return false;          

        }

        /// <summary>
        /// Indicates if the string has a value (i.e. the reverse of string.IsNullOrEmpty)
        /// </summary>
        public static bool IsNotNullOrEmpty(this string instance)
        {
            return string.IsNullOrEmpty(instance) == false;
        }

        /// <summary>
        /// Indicates whether the specified System.String object is null or an System.String.Empty string
        /// </summary>
        public static bool IsNullOrEmpty(this string instance)
        {
            return string.IsNullOrEmpty(instance);
        }
    }
}
